<?php
/***/
namespace app\admin\controller;

use app\admin\model\Adminuser;
use app\admin\model\Role;
use app\admin\model\mainUsertype;
/**
 * 用户列表
 * @Author    lf
 * @DateTime  2018-05-14T11:18:10+0800
 */
class User extends Father
{
   	//管理员页面
    public function user()
    {
        $onlyrequest = [['page', 1], ['limit', 15]];
        $request     = $this->getRequests($onlyrequest, 'GET');

        if (input('get.api')) {

            $user_m = new Adminuser;

            $uname = trim(input('uname'));
            $utype = trim(input('utype'));
            //查询处理数据
            $data = $user_m->alias('us')
                ->field('us.*,ro.role_id,ro.role_name,cha.channel_id,cha.company_name,pla.id as plat_id,pla.platfrom')
                ->join('adm_role ro',' us.role_id = ro.role_id','LEFT')
                ->join('bus_channel cha',' us.relate_id = cha.channel_id','LEFT')
                ->join('bus_platfrom pla',' us.relate_id = pla.plat_id','LEFT');
                if(isMmsOrSms()){
                    $data = $data->where('us.role_id=56 or cha.off_redis=0 ');
                }
                if($uname)
                {
                    $data = $data->where('username','like','%'.$uname.'%');
                }
                if($utype)
                {
                    $data = $data->where('user_type',$utype);
                }
                $data = $data->orderRaw("field(user_type,'admin','clerk','plat','channel')")->order('us.id')
                ->paginate($request['limit'], false, $request)
                ->each(function($item, $key) {
                    //处理数据关联账户
                    switch ($item->user_type) {
                        case 'channel':
                            $item->on_name = $item->company_name;
                            break;
                        case 'plat':
                            $item->on_name = $item->platfrom;
                            break;

                        default:
                            $item->on_name = '';
                            break;
                    }
                    //处理数据on_off
                    switch ($item->on_off) {
                        case '1':
                            $item->on_off_ = '<span class="layui-badge layui-bg-green status-kq">已开启</span>';
                            break;
                        case '0':
                            $item->on_off_ = '<span class="layui-badge status-jy">已禁用</span>';
                            break;
                        default:
                            $item->on_off_ = '<span class="layui-badge layui-bg-cyan status-pz">未配置</span>';
                            break;
                    }
                    //处理数据type
                    switch ($item->user_type) {
                        case 'admin':
                            $item->user_type = '管理员';
                            break;
                        case 'channel':
                            $item->user_type = '渠道';
                            break;
                        case 'plat':
                            $item->user_type = '通道';
                            break;
                        case 'clerk':
                            $item->user_type = '销售';
                            break;
                        default:
                            $item->user_type = '未知';
                            break;
                    }

                });

            $count    = $data->total();

            $list     = $data->toArray();

            $list     = $list['data'];

            return json(['code' => 0, 'msg' => '', 'count' => $count, 'data'  => $list ]);

        } else {

            return $this->fetch();
        }
    }

    /**
     * [userHanPage 添加用户页面]
     * @Author   lf
     * @DateTime 2018-05-16T11:43:58+0800
     * @return   [type]                   [添加用户页面]
     */
    public function userHanPage()
    {
        if ($this->request->isPost()) {

            //实例化Adminuser类
            $user_m       = new Adminuser;
            $add_user_arr = input('post.');
            $preg         = "/^[a-zA-Z0-9_-]{4,16}$/";

            if (!preg_match($preg,$add_user_arr['admin_name'])) {

                return '用户名不能含有汉字,特殊字符等,长度必须位于4~16位之间';
            }

            $res = $user_m->saveUserOne($add_user_arr);

            switch ($res) {

                case '1':
                    trace(session('username').'添加用户'.$add_user_arr['admin_name'],'info');
                    return 'success';
                    break;

                case '2':
                    return '用户存在！';
                    break;

                default:
                    return '添加失败！';
                    break;
            }
        } else {

            //获取角色
            $role     = Role::all();
            foreach ($role as $key => $value) {

                if($value['role_id'] == '1' || $value['role_auth_list'] == '*' ) {

                    unset($role[$key]);
                }
            }

            $usertype = mainUsertype::all();

            $this->assign('role', $role);
            $this->assign('usertype', $usertype);
            return $this->fetch();
        }
    }
    /**
     * [userEditPage 编辑用户]
     * @Author   lf
     * @DateTime 2018-05-16T14:51:08+0800
     * @return   [type]                   [description]
     */
    public function userEditPage()
    {
        if($this->request->isPost())
        {
            $post_arr = input("post.");
            $admin_relate = trim(input('post.admin_relate'));
            $role = trim(input('post.role'));
            // halt($post_arr);
            if($post_arr['usid']){
                $user = Adminuser::get($post_arr['usid']);
                $username = $user->username;
                // $user->user_type = trim($post_arr['type']);
                // $user->relate_id = $admin_relate;
                $user->role_id   = $role;
                $user->mark_up   = $post_arr['mark'];
                $user->name   = $post_arr['name'];

                if($user->isUpdate(true)->save())
                {
                    trace(session('username').'编辑用户'.$username,'info');
                    return 'success';
                }else{
                    return '修改失败！';
                }
            }
        }else{
            $userid = trim(input('get.usid'));

            if ($userid) {


                // $usertype = mainUsertype::all();

                $list = Adminuser::get($userid);

                //获取角色
                $role = Role::where('use_type',$list['user_type'])->select();

                foreach ($role as $key => $value) {

                    if($value['role_id'] == '1' || $value['role_auth_list'] == '*' ) {

                        unset($role[$key]);
                    }
                }

                // if (!empty($list->user_type)) {

                //     switch ($list->user_type) {
                //         case 'channel':
                //             $user_type_list =  db('bus_channel')->field('channel_id,company_name')->select();
                //             break;
                //         case 'plat':
                //             $user_type_list =  db('bus_platfrom')->field('plat_id,platfrom')->select();
                //             break;
                //         default:
                //             $user_type_list =  [];
                //             break;
                //     }

                //     $this->assign('user_type_list', $user_type_list);
                // }

                $this->assign('role', $role);
                // $this->assign('usertype', $usertype);
                $this->assign('usid', $userid);
                $this->assign('list', $list);
                return $this->fetch('user_edit');
            } else {

                return '找不到用户！';
            }
        }
    }

    /**
     * [edit 编辑用户]
     * @Author   lf
     * @DateTime 2018-05-16T14:51:28+0800
     * @return   [type]                   [description]
     */
    // public function edit()
    // {
    //     $post_arr = input("post.");
    //     if($post_arr['usid']){
    //         $user = Adminuser::get($post_arr['usid']);
    //         $username = $user->username;
    //         $user->user_type = $post_arr['type'];
    //         $user->relate_id = $post_arr['admin_relate'];
    //         $user->role_id = $post_arr['role'];
    //         $user->mark_up = $post_arr['mark'];

    //         if($user->isUpdate(true)->save())
    //         {
    //             trace(session('username').'编辑用户'.$username,'info');
    //             return true;
    //         }else{
    //             return '修改失败！';
    //         }
    //     }
    // }


    /**
     * 添加一条用户记录
     * @Author    lf
     * @DateTime  2018-05-14T11:35:48+0800
     */
    // public function setUserOne()
    // {
    //     //实例化Adminuser类
    //     $user_m = new Adminuser;
    //     $add_user_arr = input('post.');
    //     // dump($add_user_arr);
    //     // return 10;
    //     $res = $user_m->saveUserOne($add_user_arr);
    //     switch ($res) {
    //         case '1':
    //             trace(session('username').'添加用户'.$add_user_arr['admin_name'],'info');
    //             return true;
    //             break;
    //         case '2':
    //             return '用户存在！';
    //             break;

    //         default:
    //             return '添加失败！';
    //             break;
    //     }
    // }


    /**
     * 查询用户对应的渠道或者通道
     *
     */
    public function getUserType()
    {
        if(input('get.api') == 1){
            $usertype = input('get.usertype');
            if(isMmsOrSms()){
                $usertype = 'admin_mms';
            }
            //获取角色
            $role = Role::where('use_type',$usertype)->where('role_id','<>','1')->where('role_auth_list','<>','*')->order('role_id desc')->select();

            return json($role);
        }else{

            $usertype = input('get.usertype');



            switch ($usertype) {
                case 'channel':
                    if(isMmsOrSms()){
                        $where = ['off_redis'=>0];
                    }else{
                        $where = [];
                    }
                    return json(db('bus_channel')->field('channel_id,company_name')->where($where)->select());
                    break;
                case 'plat':
                    if(isMmsOrSms()){
                        $where = ['marking'=>1];
                    }else{
                        $where = [];
                    }
                    return json(db('bus_platfrom')->field('plat_id,platfrom')->where($where)->select());
                    break;
                default:
                    return '';
                    break;
            }
        }
    }

    /**
     * 开启与关闭
     */
    public function stopUser()
    {
        //实例化Adminuser类
        $user_m = new Adminuser;
        $id     = (int) input('post.uid');
        $state  = input('post.state');
        if($state == '1') {

            return $user_m->updateOnOffOne($id,'1');
        } else {

            return $user_m->updateOnOffOne($id,'0');
        }
    }

    /**
     * [del 删除用户]
     * @Author   lf
     * @DateTime 2018-05-15T14:55:00+0800
     * @return   [type]                   [返回true 成功]
     */
    public function del()
    {
        $userid = trim(input('post.usid'));

        if (!$this->allDel()) {

            return '权限不足，无法删除！请联系管理员';
        }

        $getuser = Adminuser::get($userid);

        if ($getuser['role_id'] == '1' || $getuser['username'] == 'admin') {

            return '超级管理不能删除';
        }

        if(Adminuser::destroy($userid)) {

            trace(session('username').'删除了用户'.$getuser['username'],'info');
            return true;
        } else {

            return '删除失败 ！';
        }
    }


}